import React, { Component, useState, useEffect, forwardRef, createRef, useImperativeHandle } from 'react'
import { connect, } from 'react-redux'
import { View, Text, StyleSheet, SafeAreaView, ScrollView, TouchableOpacity, TouchableWithoutFeedback, TextInput, Modal, FlatList } from 'react-native'
import { pTx } from "../../utils/dimensions"
import { IconFill, IconOutline } from "@ant-design/icons-react-native";
import { useRealm, useQuery } from '@realm/react'
import { schemaName } from "../../realm"
import Realm from "realm"
import LinearGradient from 'react-native-linear-gradient';
import defRpcUrlList from "../../utils/rpcUrlList"
import NetworkList from "../../utils/NetworkList"

const AddCustomNetwork = forwardRef((props, ref) => {
    const [open, setOpen] = useState(false)
    const [rpcUrl, setRpcUrl] = useState(null)
    const [rpcUrlName, setRpcUrlName] = useState(null)
    const realm = useRealm();
    const wallet = useQuery(schemaName.Wallet, wallet => {
        return wallet.filtered('current = true');
    })[0];
    useImperativeHandle(ref, () => ({
        setOpen,
    }))
    const addNetwork = async () => {
        if (!rpcUrlName || !rpcUrl) return

        realm.write(() => {
            realm.create(schemaName.RpcUrl, {
                _id: new Realm.BSON.UUID(),
                chainId: wallet.chainId || 1,
                rpcUrlName,
                rpcUrl,
            }, true);
        })
        setOpen(false)
    }
    return (
        <Modal
            visible={open}
            animationType="fade"
            transparent={true}
        >
            <View style={styles.centeredView}>
                <View style={styles.modalView}>
                    <Text style={styles.modalViewName}>添加自定义节点</Text>
                    <TextInput style={styles.textareaItem}
                        onChangeText={(value) => {
                            setRpcUrlName(value)
                        }} />
                    <TextInput style={[styles.textareaItem, { textAlignVertical: 'top', }]} numberOfLines={4} multiline={true}
                        onChangeText={(value) => {
                            setRpcUrl(value)
                        }} />
                    <View style={styles.ModalFoot}>
                        <Text style={styles.close} onPress={() => setOpen(false)}>取消</Text>
                        <TouchableOpacity style={[styles.sure]} onPress={addNetwork}>
                            <LinearGradient
                                colors={['rgba(51, 225, 144, 1)', 'rgba(68, 225, 240, 1)']}
                                start={{ x: 0.25, y: 0.25 }}
                                end={{ x: 0.75, y: 0.75 }}
                                style={styles.linearGradient}
                            >
                                <Text>确认</Text>
                            </LinearGradient>
                        </TouchableOpacity>
                    </View>
                </View>
            </View>
        </Modal>
    )
})

const NetworFlatList = () => {
    const realm = useRealm();
    const wallet = useQuery(schemaName.Wallet, wallet => {
        return wallet.filtered('current = true');
    })[0];
    const rpcUrlList = useQuery(schemaName.RpcUrl, rpcUrl => {
        return rpcUrl.filtered(`chainId == ${wallet.chainId}`);
    })
    const rpcUrlListcurrentMark = useQuery(schemaName.RpcUrl, rpcUrl => {
        return rpcUrl.filtered(`chainId == ${wallet.chainId} and currentMark = true`);
    })[0]
    const setRpcUrl = (item) => {
        realm.write(() => {
            for (const rpcUrl of rpcUrlList) {
                console.log(item.currentMark)
                if (item._id == undefined) {
                    rpcUrl.currentMark = false
                } else {
                    if (item._id + "" == rpcUrl._id + "") {
                        rpcUrl.currentMark = true
                    } else {
                        rpcUrl.currentMark = false
                    }
                }

            }
        });
    }
    return (
        <FlatList
            style={{ flex: 1 }}
            renderItem={({ item, index }) => {
                return (
                    <View>
                        <TouchableWithoutFeedback onPress={() => setRpcUrl(item)} >
                            <View style={styles.li}>
                                <View>
                                    <View style={styles.flexDirectionRow}>
                                        <Text style={styles.label}>{item.rpcUrlName || item.nickname}</Text>
                                        {
                                            item.currentMark && <IconOutline name="check" style={styles.icon} />
                                        }
                                        {
                                            !rpcUrlListcurrentMark && !item._id && <IconOutline name="check" style={styles.icon} />
                                        }

                                    </View>
                                    <Text style={styles.cel}>{item.rpcUrl}</Text>
                                </View>
                                <View>
                                    <View style={[styles.flexDirectionRow, { justifyContent: "flex-end", }]}>
                                        <Text style={styles.label}>562 ms</Text>
                                        <Text style={[styles.black, { backgroundColor: "#06C161" }]}></Text>
                                    </View>
                                    <Text style={[styles.cel, { alignSelf: "flex-end" }]}>区块高度34797864</Text>
                                </View>
                            </View>
                        </TouchableWithoutFeedback>
                    </View>
                )
            }}
            data={rpcUrlList.concat(NetworkList.filter(item => item.chainId == wallet.chainId)).reverse()}
            keyExtractor={(item, index) => index}
        />
    )
}


export class CustomNetwork extends Component {
    constructor(props) {
        super(props)
        this.state = {
            rpcUrlList: []
        }
        this.addCustomNetworkRefs = createRef();
    }
    load = async () => {
        // let RpcUrlList = await realm.objects(schemaName.RpcUrlList);
        // let list = RpcUrlList.filtered(`chainId == ${this.props.Wallet.chainId}`)
        // this.setState({
        //     rpcUrlList: list.concat(defRpcUrlList).reverse()
        // })
    }
    setRpcUrl = async (item) => {
        // realm.write(() => {
        //     realm.create(schemaName.CurrentRpcUrl, item, true);
        // })
        // this.props.asyncNetworkRpc()
    }
    componentDidMount = () => {
        // this.load()
    }
    render() {
        return (
            <SafeAreaView style={styles.page}>
                <View style={styles.txtBox}>
                    <View style={styles.txt}>
                        <Text style={styles.text}>节点速度 </Text>
                        <Text style={[styles.black, { backgroundColor: "#06C161" }]}></Text>
                        <Text style={styles.text}>快</Text>
                        <Text style={[styles.black, { backgroundColor: "#EBAE1F" }]}></Text>
                        <Text style={styles.text}>中</Text>
                        <Text style={[styles.black, { backgroundColor: "#EA6055" }]}></Text>
                        <Text style={styles.text}>慢</Text>
                    </View>
                    <Text style={[styles.text, { marginTop: pTx(5) }]}>区块高度：高度值越大，代表节点数据同步更完善，其稳定性更好。在节点速度差不多的情况下，选择高度值大的节点，体验更好</Text>
                </View>
                <Text style={styles.name}>推荐节点</Text>
                <View style={styles.list}>
                    {/* {this.state.rpcUrlList.map((item, index) => {
                            const isNetwork = this.props.NetworkList.find(net => net.chainId == item.chainId).rpcUrl == item.rpcUrl
                            return (
                               
                            )
                        })} */}
                    <NetworFlatList {...this.props} />
                    <TouchableOpacity><Text style={styles.button} onPress={() => this.addCustomNetworkRefs.setOpen(true)}>添加自定义节点</Text></TouchableOpacity>
                </View>
                <AddCustomNetwork ref={el => this.addCustomNetworkRefs = el} load={this.load} {...this.props} />
            </SafeAreaView>
        )
    }
}

const mapStateToProps = state => state.wallet

const mapDispatchToProps = {
}

export default connect(mapStateToProps, mapDispatchToProps)(CustomNetwork)

const styles = StyleSheet.create({
    page: {
        flex: 1,
        borderTopRightRadius: pTx(15),
        borderTopLeftRadius: pTx(15),
        backgroundColor: "#EDEDED",
    },
    txtBox: {
        marginHorizontal: pTx(15),
        paddingHorizontal: pTx(15),
        paddingVertical: pTx(20),
        backgroundColor: "#F7F7F7",
        borderRadius: pTx(6),
    },
    txt: {
        flexDirection: 'row',
        alignItems: "center",
    },
    text: {
        fontSize: pTx(12),
        color: "#AFB5BD",
        lineHeight: pTx(16),
    },
    black: {
        marginHorizontal: pTx(5),
        width: pTx(5),
        height: pTx(5),
        borderRadius: pTx(5),
    },
    name: {
        marginTop: pTx(20),
        fontSize: pTx(12),
        color: "#0A0C14",
        lineHeight: pTx(12),
        marginHorizontal: pTx(15),
    },
    list: {
        flex: 1,
        marginTop: pTx(12),
        paddingHorizontal: pTx(15),
        backgroundColor: "#fff"
    },
    flexDirectionRow: {
        flexDirection: 'row',
        justifyContent: "space-between",
        alignItems: "center",
    },
    li: {
        paddingVertical: pTx(15),
        flexDirection: 'row',
        justifyContent: "space-between",
        alignItems: "center",
        borderBottomWidth: 1,
        borderBottomColor: "rgba(175,181,189,0.15)",
    },
    label: {
        fontSize: pTx(14),
        color: "#0A0C14",
    },
    cel: {
        marginTop: pTx(5),
        fontSize: pTx(12),
        color: "#AFB5BD",
    },
    icon: {
        marginLeft: pTx(15),
        fontSize: pTx(14),
        color: "#2b7ffb",
    },
    button: {
        paddingVertical: pTx(20),
        alignSelf: "center",
        fontSize: pTx(14),
        color: "#2B7FFB",
    },
    textareaItem: {
        marginTop: pTx(20),
        backgroundColor: "#F7F7F7",
        borderRadius: pTx(6),
        borderColor: "#F7F7F7",
        borderWidth: 0,
        fontSize: pTx(16),
        height: "auto",
        paddingHorizontal: pTx(15),
        paddingVertical: pTx(10),
    },
    ModalFoot: {
        marginTop: pTx(20),
        flexDirection: 'row',
        justifyContent: "space-between",
        alignItems: "center",
    },
    close: {
        flex: 1,
        textAlign: "center",
        textAlignVertical: "center",
        maxWidth: pTx(120),
        height: pTx(45),
        fontSize: pTx(14),
        color: "#0A0C14",
        backgroundColor: 'rgba(243, 245, 248, 0.6)',
        borderRadius: pTx(4),
        // border: 1px solid #CCCCCC;
        borderColor: "rgba(204, 204, 204, 0.3)",
        borderWidth: 1
    },
    sure: {
        flex: 1,
        flexDirection: 'row',
        justifyContent: "center",
        alignItems: "center",
        maxWidth: pTx(120),
        height: pTx(45),
        borderRadius: pTx(4),
        borderColor: "rgba(204, 204, 204, 0.3)",
        borderWidth: 1
    },
    linearGradient: {
        flex: 1,
        height: pTx(45),
        flexDirection: 'row',
        justifyContent: "center",
        alignItems: "center",
        fontSize: pTx(14),
        color: "#0A0C14",
        borderRadius: pTx(4),
    },
    centeredView: {
        flex: 1,
        justifyContent: "center",
        alignItems: "center",
        backgroundColor: "rgba(0,0,0,0.2)",
    },
    modalView: {
        width: pTx(300),
        paddingHorizontal: pTx(20),
        paddingVertical: pTx(30),
        backgroundColor: "white",
        borderRadius: pTx(10),
        shadowColor: "rgba(0,0,0,0.5)",
        shadowOffset: {
            width: 0,
            height: 1
        },
        shadowOpacity: 0.1,
        shadowRadius: 1,
        elevation: 5,
        backgroundColor: "#fff",
    },
    modalViewName: {
        fontSize: pTx(16),
        color: "#0A0C14",
        textAlign: "center"
    },

})